#!/usr/bin/python

"""
GPL License jazz, goog_pam is (c)Rich Lundeen


This python program is specific to pam-google
It is called as follows

name google_username, new_google_password

It needs to be called with the right permissions to read the config file


On Success it returns 0

On Error - it returns one of the following:
-1 forking error
2 bad usage
3 admin username/password error or network error
4 username doesn't exist
5 the prog does not have authentication
6 config file error
7 args too long
8 captcha error
42 unhandled google error
""" 

import sys 
import gdata.apps.service
import getpass
import os
import ConfigParser
import struct

class googpass:
  def __init__(self, uname, password, configfile="/etc/security/goog_pam/goog_pam.conf", hash_func="SHA-1"):
    self.user_name = uname
    self.user_password = password
    self.admin_name = None
    self.admin_password = None
    self.domain = None
    self.hash_func = hash_func
    self.getadmininfo(configfile)
    self.pwchange()

  def getadmininfo(self, configfile):
    config = ConfigParser.ConfigParser()
    config.read(configfile)
    self.admin_name = config.get("global", "admin_email")
    self.admin_password = config.get("global", "password")
    self.domain = config.get("global", "domain")
 
  def pwchange(self):
    """it would be nice to have an api where users can change their own passwords - but we work with the api we've got
       unfortunately, this means the password part of the module will not work with standard gmail"""
    service = gdata.apps.service.AppsService(email=self.admin_name, domain=self.domain, password=self.admin_password)
    service.ProgrammaticLogin()
    user = service.RetrieveUser(self.user_name)
    user.login.password=self.user_password
    user.login.hash_function_name=self.hash_func
    service.UpdateUser(self.user_name, user)


if __name__ == "__main__":
  try:
    mpw = googpass(sys.argv[1], sys.argv[2])
  except IndexError:
    #bad usage
    sys.exit(2)
  except gdata.service.BadAuthentication:
    #could not login with administrator
    sys.exit(3)
  except gdata.apps.service.AppsForYourDomainException:
    sys.exit(4)
  except gdata.service.CaptchaRequired:
    return 8
  except:
    sys.exit(42)

  sys.exit(0)
